import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import mongoose from 'mongoose'
import path from 'path'
import bodyParser from 'body-parser'
import _debug from 'debug'
import express from 'express'
//Config File
import webpack_dev_config from '../internals/webpack/webpack.config.dynamic'
import config from '../config'
// Session Dependency
import passport from 'passport'
import session from 'express-session'
import connectMongo from 'connect-mongo'


const debug = _debug('app:server')

// Server
const app = new (require('express'))()
const port = config.server_port

// Server Utilities
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// Database
mongoose.connect(config.mongo.uri, config.mongo.options)
mongoose.connection.on('error', function(err) {
    console.error(`MongoDB connection error: ${err}`)
    process.exit(-1); // eslint-disable-line no-process-exit
})





// Serve Front Assets.
if (config.env === 'development') {
  
  // Webpack, Dev and Hot, Both Are Only In Development Mode. * Production Will Be Different. Still Working on This. *
  const compiler = webpack(webpack_dev_config)
  app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpack_dev_config.output.publicPath }))
  app.use(webpackHotMiddleware(compiler))
  // Routes. * Production Will Be Different. Still Working on This. *

  // Serve static assets from ~/Client/public since Webpack is unaware of
  // these files. This middleware doesn't need to be enabled outside
  // of development since this directory will be copied into ~/dist
  // when the application is compiled.
  const client_public = path.join ( __dirname, '..', '/client','/static' );
  app.use('/',express.static(client_public));

} else {

  const client_public = path.join ( __dirname, '..', '/dist' );
  app.use('/',express.static(client_public));

}

// Serve Server-Side API.
// Include the Server API Routes and sendFile index.html, it will be different in production mode.
// * Production Will Be Different. Still Working on This. *
require('./server-routes')(app);







// Session
const MongoStore = connectMongo(session)
app.use(passport.initialize())
// Persist sessions with MongoStore / sequelizeStore
// We need to enable sessions for passport-twitter because it's an
// oauth 1.0 strategy, and Lusca depends on sessions
app.use(session({
  secret: config.secrets.session,
  saveUninitialized: true,
  resave: false,
  store: new MongoStore({
    mongooseConnection: mongoose.connection,
    db: 'redux-page-luke-session-store'
  })
}))




// Begin Listen.
app.listen(port, function(error) {
  if (error) {
    console.error(error)
  } else {
    console.info("==> 🌎  Listening on port %s. Open up http://localhost:%s/ in your browser.", port, port)
  }
})

